import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import LoginView from '../views/LoginView.vue'
import { useMainStore } from '../../stores/index'
const cors = require('cors')
app.use(cors())
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'login',
      component: LoginView,
    },
    {
      //用户界面
      path: '/usermap',
      name: 'usermap',
      component: () => import('../views/UsermapView.vue'),
    },
    {
      //管理员界面
      path: '/admin',
      name: 'admin',
      component: () => import('../views/AdministrationView.vue'),
    },
    {
      //交管界面
      path: '/traffic',
      name: 'traffic',
      component: () => import('../views/TrafficmapView.vue'),
    },
    //注册页面
    {
      path: '/register',
      name: 'register',
      component: () => import('../views/RegisterView.vue'),
    },
    {
      path: '/event-manage',
      name: 'event-manage',
      component: () => import('../views/EventManageView.vue'),
    },
  ],
})

router.beforeEach((to, from, next) => {
  const store = useMainStore()
  // 需要登录的页面
  const authPages = ['/usermap', '/admin', '/traffic']
  if (authPages.includes(to.path)) {
    if (!store.token) {
      return next('/register')
    }
  }
  next()
})

export default router
